package cn.iocoder.yudao.module.system.service.gugu;

import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.ExaminationResult;
import cn.iocoder.yudao.module.system.dal.dataobject.gugu.ScoreSegmentDO;
import cn.iocoder.yudao.module.system.dal.mysql.gugu.ScoreSegmentMapper;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 高考一分一段数据 Service 实现类
 */
@Service
@Slf4j
public class ScoreSegmentServiceImpl implements ScoreSegmentService {

    @Resource
    private ScoreSegmentMapper scoreSegmentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveScoreSegmentList(List<ExaminationResult> scoreSegmentList, String year, String provinceName, String subjectSelection) {
        if (scoreSegmentList == null || scoreSegmentList.isEmpty()) {
            return 0;
        }

        int savedCount = 0;
        int skippedCount = 0;

        for (ExaminationResult result : scoreSegmentList) {
            // 检查是否已存在相同的记录
            boolean exists = scoreSegmentMapper.existsByYearAndProvinceAndSubjectAndScore(
                    year, provinceName, subjectSelection, result.getExaminationScore());

            if (exists) {
                skippedCount++;
                log.debug("跳过已存在的记录: 年份={}, 省份={}, 科目选择={}, 分数={}",
                        year, provinceName, subjectSelection, result.getExaminationScore());
                continue;
            }

            // 将历史分数数据转换为JSON字符串
            String historicalScoresJson = null;
            if (result.getHistoricalScores() != null && !result.getHistoricalScores().isEmpty()) {
                historicalScoresJson = JsonUtils.toJsonString(result.getHistoricalScores());
            }

            // 创建新记录
            ScoreSegmentDO scoreSegment = ScoreSegmentDO.builder()
                    .year(year)
                    .provinceName(provinceName)
                    .subjectSelection(subjectSelection)
                    .examinationScore(result.getExaminationScore())
                    .candidateCount(result.getCandidateCount())
                    .totalCandidates(result.getTotalCandidates())
                    .rankingRange(result.getRankingRange())
                    .admissionBatchName(result.getAdmissionBatchName())
                    .minimumAdmissionScore(result.getMinimumAdmissionScore())
                    .ranking(result.getRanking())
                    .historicalScores(historicalScoresJson)
                    .build();

            // 保存到数据库
            scoreSegmentMapper.insert(scoreSegment);
            savedCount++;
        }

        if (skippedCount > 0) {
            log.info("保存一分一段数据完成: 新增{}条, 跳过重复{}条", savedCount, skippedCount);
        } else {
            log.info("保存一分一段数据完成: 新增{}条", savedCount);
        }

        return savedCount;
    }

    @Override
    public List<ScoreSegmentDO> getScoreSegmentList(String year, String provinceName, String subjectSelection) {
        return scoreSegmentMapper.selectByYearAndProvinceAndSubject(year, provinceName, subjectSelection);
    }

    @Override
    public ScoreSegmentDO getScoreSegmentByScore(String year, String provinceName, String subjectSelection, String score) {
        return scoreSegmentMapper.selectByYearAndProvinceAndSubjectAndScore(year, provinceName, subjectSelection, score);
    }

    @Override
    public boolean existsScoreSegment(String year, String provinceName, String subjectSelection) {
        return scoreSegmentMapper.existsByYearAndProvinceAndSubject(year, provinceName, subjectSelection);
    }

    @Override
    public List<ScoreSegmentDO> getScoreSegmentListByCondition(String year, String provinceName, String subjectSelection,
                                                             String minScore, String maxScore, String batchName) {
        // 先尝试正常查询
        List<ScoreSegmentDO> scoreSegmentDOS = scoreSegmentMapper.selectByYearAndProvinceAndSubjectAndCondition(year, provinceName, subjectSelection,
                minScore, maxScore, batchName);

        // 如果没有找到数据，则尝试处理区间分数的情况
        if (scoreSegmentDOS == null || scoreSegmentDOS.isEmpty()) {
            // 如果有指定的分数，尝试查找包含该分数的区间
            if (maxScore != null && !maxScore.isEmpty()) {
                try {
                    Double exactScore = Double.parseDouble(maxScore);
                    ScoreSegmentDO segmentDO = scoreSegmentMapper.selectByYearAndProvinceAndSubjectAndExactScore(
                            year, provinceName, subjectSelection, exactScore.intValue());
                    if (segmentDO != null) {
                        // 找到了包含该分数的区间，将其添加到结果中
                        scoreSegmentDOS = new ArrayList<>();
                        scoreSegmentDOS.add(segmentDO);
                        return scoreSegmentDOS;
                    }
                } catch (NumberFormatException e) {
                    // 如果分数不是数字格式，忽略异常
                    log.warn("分数格式不正确: {}", maxScore);
                }
            }

            // 如果上述方法仍然没有找到数据，并且用户输入的最大分数不是750分，则尝试使用750作为最大分数再次查询
            if ((scoreSegmentDOS == null || scoreSegmentDOS.isEmpty()) && !"750".equals(maxScore)) {
                return scoreSegmentMapper.selectByYearAndProvinceAndSubjectAndCondition(year, provinceName, subjectSelection,
                        minScore, "750", batchName);
            }
        }

        return scoreSegmentDOS;
    }

    @Override
    public Map<String, Object> fetchAndSaveScoreSegment(String appkey, String year, String provinceName, String subjectSelection) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证appkey是否有效
            if (!GuGuDataUtils.validateScoreApiKey(appkey)) {
                result.put("success", false);
                result.put("message", "无效的APPKEY");
                return result;
            }

            // 直接从 API 获取数据，不检查数据库

            // 从API获取数据
            List<ExaminationResult> allResults = new ArrayList<>();
            int currentPage = 1;
            int totalPages = 1;
            int totalCount = 0;

            // API最大允许的pageSize是20
            final int pageSize = 20;

            // 获取第一页数据，同时获取总数据量
            String firstPageJson = GuGuDataUtils.getScoreSegmentJson(subjectSelection, year, provinceName, currentPage, pageSize);
            List<ExaminationResult> firstPageResults = GuGuDataUtils.extractExaminationResult(firstPageJson);
            totalCount = GuGuDataUtils.getTotalCount(firstPageJson);

            if (firstPageResults == null || firstPageResults.isEmpty()) {
                result.put("success", false);
                result.put("message", "未找到相关数据");
                return result;
            }

            // 添加第一页数据
            allResults.addAll(firstPageResults);

            // 计算总页数
            totalPages = (int) Math.ceil((double) totalCount / pageSize);

            // 获取剩余页数据
            for (currentPage = 2; currentPage <= totalPages; currentPage++) {

                List<ExaminationResult> pageResults = GuGuDataUtils.getExaminationResults(
                        subjectSelection, year, provinceName, currentPage, pageSize);

                if (pageResults != null && !pageResults.isEmpty()) {
                    allResults.addAll(pageResults);
                }
            }

            // 保存数据到数据库
            int savedCount = saveScoreSegmentList(allResults, year, provinceName, subjectSelection);

            result.put("success", true);
            result.put("message", "成功获取并保存了" + savedCount + "条数据");
            result.put("data", allResults);
            result.put("totalCount", totalCount);
            result.put("fromDatabase", false);

            return result;
        } catch (Exception e) {
            log.error("获取一分一段数据失败", e);
            result.put("success", false);
            result.put("message", "获取一分一段数据失败: " + e.getMessage());
            return result;
        }
    }
}
